package com.three.crm.fragment;

import android.app.DatePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.three.crm.R;
import com.three.crm.adapter.ArrivalListAdapter;
import com.three.crm.adapter.CompanyListAdapter;
import com.three.crm.base.BaseFragment;
import com.three.crm.bean.CommonBean;
import com.three.crm.bean.CompanyBean;
import com.three.crm.constant.AppConstant;
import com.three.crm.http.CommonResultCallBack;
import com.three.crm.require.AppRequireService;
import com.three.crm.util.AppManager;
import com.three.crm.util.GsonUtils;
import com.three.crm.util.SignUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Calendar;
import java.util.List;

import okhttp3.Call;

public class ArrivalFragment extends BaseFragment {

    public ArrivalFragment() {}

    public static ArrivalFragment newInstance(int index, String title) {
        ArrivalFragment fragment = new ArrivalFragment();
        Bundle args = new Bundle();
        args.putInt(AppConstant.INDEX, index);
        args.putString(AppConstant.KEY_TITLE, title);
        fragment.setArguments(args);
        return fragment;
    }

    private EditText etInput;
    private View mLoadingView;
    private TextView tvLoading,tvTime;
    private ImageView ivState;
    private ProgressBar progressBar;
    private SwipeRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private ArrivalListAdapter adapter;
    private int pageNo = 1;
    private boolean isloadMore = false;
    private String keyWord = "";
    private int type = 1;

    private DatePickerDialog datePickerDialog;
    private String carTime = "";
    private int curYear, monthOfYear, dayOfMonth;

    @Override
    protected void initArguments(Bundle bundle) {
        if (bundle != null) {
            type = bundle.getInt(AppConstant.INDEX);
        }
    }

    @Override
    protected int bindLayout() {
        return R.layout.fragment_arrival;
    }

    @Override
    protected void initViews(View view, Bundle savedInstanceState) {
        tvTime = $(R.id.tv_time);
        etInput = $(R.id.et_input);
        refreshLayout = $(R.id.refresh_layout);
        mLoadingView = LayoutInflater.from(getActivity()).inflate(R.layout.loading_view,null);
        ivState = mLoadingView.findViewById(R.id.iv_state);
        tvLoading = mLoadingView.findViewById(R.id.tv_loading);
        progressBar = mLoadingView.findViewById(R.id.progressBar);

        recyclerView = $(R.id.recycleview);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(linearLayoutManager);
        adapter = new ArrivalListAdapter();
        recyclerView.setAdapter(adapter);

        //初始化日历
        Calendar calendar = Calendar.getInstance();
        curYear = calendar.get(Calendar.YEAR);
        monthOfYear = calendar.get(Calendar.MONTH);
        dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
    }

    @Override
    public void initListener() {
        tvTime.setOnClickListener(this);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshing();
            }
        });
        tvLoading.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshing();
            }
        });
        adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                recyclerView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (isloadMore) {
                            pageNo ++;
                            loadData();
                        }
                    }
                },1000);
            }
        },recyclerView);

        etInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                keyWord = s.toString();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshing();
                    }
                },500);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()){
            case R.id.tv_time:
                onSelectTime();
                break;
        }
    }

    private void onSelectTime() {
        datePickerDialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear,
                                  int dayOfMonth) {
                String text = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
                carTime = text;
                tvTime.setText(text);
                refreshing();
            }
        }, curYear, monthOfYear, dayOfMonth);
        datePickerDialog.show();
    }

    @Override
    protected void initData(Context context) {
        refreshing();
    }

    private void refreshing() {
        if (refreshLayout != null && refreshLayout.isRefreshing()) {
            refreshLayout.setRefreshing(true);
        }
        progressBar.setVisibility(View.VISIBLE);
        tvLoading.setText(getActivity().getString(R.string.loading));
        ivState.setVisibility(View.GONE);
        adapter.setEnableLoadMore(true);
        adapter.getData().clear();
        pageNo = 1;
        isloadMore = false;
        loadData();
    }

    private void loadData() {
        adapter.setEmptyView(mLoadingView);
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("userToken", AppManager.getToken());
            jsonObject.put("type",type);
            jsonObject.put("time",carTime);
            jsonObject.put("pageNo",pageNo);
            jsonObject.put("pageSize",AppConstant.PAGE_SIZE);
            jsonObject.put("keyword",keyWord);
            jsonObject.put("timestamp",getTimestamp());
            String sign = SignUtil.genSign(jsonObject);
            jsonObject.put("sign",sign);
            Log.i("TAG","jsonObject="+jsonObject.toString());
            AppRequireService.queryArrivalInfoList(getActivity(), AppConstant.QUERY_LIST, jsonObject, new CommonResultCallBack(getActivity()) {
                @Override
                public void onResult(String result, int requireCode) {
                    Log.i("TAG","result="+result);
                    resetRefresh();
                    if (requireCode == AppConstant.QUERY_LIST) {
                        List<CommonBean> tempList = GsonUtils.parseJsonArrayWithGson(result,CommonBean.class);
                        Log.i("TAG","list="+tempList.size());
                        setListAdapter(tempList);//设置页面数据
                    }
                }

                @Override
                public void onConnectTimeOut(Call call, Exception e, int requireCode) {
                    resetRefresh();
                    showToast(e.getMessage());
                    setState(getActivity().getString(R.string.connect_time_out),R.mipmap.ic_http_error);
                }

                @Override
                public void onFail(String msg, int requireCode) {
                    resetRefresh();
                    showToast(msg);
                    adapter.loadMoreFail();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void setListAdapter(List<CommonBean> mList) {
        resetRefresh();
        if (isloadMore) {
            adapter.addData(mList);
            if (mList.size() < AppConstant.PAGE_SIZE) {
                adapter.loadMoreEnd();
            } else {
                adapter.loadMoreComplete();
                adapter.setEnableLoadMore(true);
            }
        } else if (mList.isEmpty()) {
            adapter.loadMoreEnd();
            adapter.setEnableLoadMore(false);
            setState(getActivity().getString(R.string.no_data),R.mipmap.ic_empty);
        } else {
            adapter.setNewData(mList);
            adapter.loadMoreComplete();
            adapter.setEnableLoadMore(true);
            isloadMore = true;
        }
    }

    private void setState(String string, int resId) {
        try {
            progressBar.setVisibility(View.GONE);
            tvLoading.setText(string);
            ivState.setImageResource(resId);
            ivState.setVisibility(View.VISIBLE);
            adapter.setEmptyView(mLoadingView);
            adapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void resetRefresh() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.setRefreshing(false);
        }
        progressBar.setVisibility(View.GONE);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        resetRefresh();
    }
}
